package com.example.tys.baseapplication.net_tcp.protocol.tcp.ShortConnection;


import com.example.tys.baseapplication.net_tcp.frame.ConnectStatus;
import com.example.tys.baseapplication.net_tcp.frame.NettyImpl.tcp.BaseTcpClient;
import com.example.tys.baseapplication.net_tcp.frame.PacketRequest;
import com.example.tys.baseapplication.net_tcp.frame.PacketResponse;

import java.net.InetSocketAddress;

import io.netty.channel.ChannelHandlerContext;

/**
 *
 * @author tys
 * @date 2019/5/5
 */

public abstract class TcpClient extends BaseTcpClient<PacketRequest, PacketResponse> {

    @Override
    protected int getAllIdleTimeout() {
        return 30;
    }

    @Override
    protected void allIdle(ChannelHandlerContext ctx) {
        ctx.close();
    }

    @Override
    protected boolean beforeSend(PacketRequest packetRequest) {
        InetSocketAddress targetAddress = packetRequest.getTargetAddress();
        if (targetAddress == null) {
            throw new RuntimeException("targetAddress can not be empty");
        }
        if (getConnectStatus() == ConnectStatus.CONNECT_SUCCEED) {
            if (targetAddress.equals(getInetSocketAddress())) {
                return super.beforeSend(packetRequest);
            } else {
                //已经连接 但是地址不同
                disConnect();
                ConnectStatus connectStatus = connectSync(targetAddress);
                if (connectStatus == ConnectStatus.CONNECT_SUCCEED) {
                    return super.beforeSend(packetRequest);
                } else {
                    return true;
                }
            }
        } else {
            ConnectStatus connectStatus = connectSync(targetAddress);
            if (connectStatus == ConnectStatus.CONNECT_SUCCEED) {
                return super.beforeSend(packetRequest);
            } else {
                return true;
            }
        }
    }
}
